﻿using Elio.Controls;
using Elio.Interfaces;
using Elio.Sessions;
using Elio.Sessions.Widgets;
using Google.Protobuf.WellKnownTypes;

namespace Elio.Widgets;

public class WidgetProgressBar : ProgressBar, ISessionWidget
{
    public BaseSession? Session { get; set; }
    public void Init(InitOptions options)
    {
        (WidthRequest, HeightRequest) = (options.Width, options.Height);
        this.SetPoint(options.X, options.Y);
    }

    public async Task<bool> OnViewReceive(string name, long sid, long fid, params Any[] argv)
    {
        switch (name)
        {
            case "getRange":
                await GetRange(sid, fid);
                break;

            case "setRange":
                SetRange();
                break;

            case "getValue":
                await GetValue(sid, fid);
                break;

            case "setValue":
                SetValue(argv);
                break;

            default:
                return false;
        }
        return true;
    }

    private async Task GetRange(long sid, long fid) =>
        await Session!.SendAction("onGetRange", sid, fid, 0.ToAny(), 1.ToAny());

    private static void SetRange() { /*Range 0..1, can not setting*/ }

    private async Task GetValue(long sid, long fid) =>
        await Session!.SendAction("onGetValue", sid, fid, Progress.ToAny());

    private void SetValue(params Any[] argv)
    {
        double p = argv[0].P2Double();
        p = p < 0 ? 0 : p;
        p = p > 1 ? 1 : p;

        Progress = p;
    }
}